package com.comtime.mybox;

import java.util.Timer;
import java.util.TimerTask;

import com.comtime.service.MyService;
import com.comtime.smartbox.BaseActivity;
import com.comtime.smartbox.HBApplication;
import com.comtime.smartkilimanjaro.R;
import com.comtime.utils.Util;
import com.comtime.view.MyDialog;
import com.comtime.view.MyProgressDialog;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;

public class OADActivity extends BaseActivity {
	String TAG = "OADActivity";
	HBApplication application;
	private TextView tv_percent, tv_time_left;
	TextView tv_log;
	private ProgressBar mProgressBar;

	int needOADNum=1;// 需要升级的设备个数
	int currentTag;

	int delayCheckTime = 55;// 15秒

	int totalTime;
	int perTotalTime;
	float OADProgress;// OAD进度

	Handler handler = new Handler();

	MyProgressDialog myProgressDialog;

	float progressDelta;

	public static final String FW_FILE_MAIN_A = "ImageA.bin";
	public static final String FW_FILE_MAIN_B = "ImageB.bin";
 

	int[] oldVer = new int[] { -1, -1 };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		application = (HBApplication) this.getApplication();
		setContentView(R.layout.activity_oad);
		setUpViews();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MyService.ACTION_CONNECTED);
		filter.addAction(MyService.ACTION_DISCONNECTED);
		filter.addAction(MyService.ACTION_OADProgress);
		registerReceiver(receiver, filter);

 
		Log.e(TAG, "needOADNum: " + needOADNum);
		myProgressDialog = new MyProgressDialog(this);
		myProgressDialog.setCancelable(false);
		myProgressDialog.show();

		startOAD();

	//	application.inForegroundOAD=true;
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}
	
	@Override
	public void onBackPressed() {
	}

	private void setUpViews() {
		tv_time_left = (TextView) findViewById(R.id.tv_time_left);
		tv_percent = (TextView) findViewById(R.id.tv_percent);
		mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
		tv_log = (TextView) findViewById(R.id.tv_log);
	}

	private void startOAD() {
		Log.e(TAG, "startOAD  currentTag: " + currentTag);
		addLog("startOAD  currentTag: " + currentTag);
		oldVer[currentTag] = application.swDevicesList.get(currentTag).versionCode;

		application.swDevicesList.get(currentTag).isOADing = true;

		application.swDevicesList.get(currentTag).disconnect();

		// 超时检测

		handler.postDelayed(checkOverTimeRunnable, (15*(currentTag+1)) * 1000);

	}

	Runnable checkOverTimeRunnable = new Runnable() {

		@Override
		public void run() {
			if (!application.swDevicesList.get(currentTag).isProgramming()) {// 10s之后没有在发送数据，超时
				myProgressDialog.dismiss();
				showDialogWithContent(getString(R.string.oad_fail));
				application.swDevicesList.get(currentTag).isOADing = false;
				application.swDevicesList.get(currentTag).stopOAD();
			}
		}
	};

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(
					MyService.ACTION_CONNECTED)) {
				 
				Log.e(TAG, "连接成功: "  + "  isOADing:"
						+ application.swDevicesList.get(0).isOADing);
				if (!application.swDevicesList.get(0).isOADing
						|| OADProgress >= 1) {
					return;
				}
				Log.e(TAG, "设备 " +  "  开始 发送OAD数据 ");
				handler.removeCallbacks(sendRunnable);
				handler.postDelayed(sendRunnable, 5 * 1000);// 5秒之后再发送是因为
															// 有可能出现瞬间多次重连断开的情况，
			} else if (intent.getAction().equals(
					MyService.ACTION_DISCONNECTED)) {

			 
				addLog(" ACTION_DeviceDisConnected ");
				
				 
				
				if(OADProgress==0){
					//OAD初始断开
				}else if(OADProgress>0 && OADProgress<1 && OADProgress!=(1.0/needOADNum)){
					//OAD过程中断线了，需提示OAD失败
					application.swDevicesList.get(0).stopOAD();
					application.swDevicesList.get(0).isOADing=false;
					
					showDialogWithContent(getString(R.string.oad_fail));
				}
				
			} else if (intent.getAction().equals(
					MyService.ACTION_OADProgress)) {

				if (myProgressDialog.isShowing()) {
					myProgressDialog.dismiss();
				}

				float progress = intent.getFloatExtra(
						MyService.EXTRA_OADProgress, 0);
				int timeLeft = intent.getIntExtra(
						MyService.EXTRA_OADTimeLeft, 0);

				OADProgress = progressDelta + progress / (needOADNum);
				if (OADProgress >= 1) {
					application.swDevicesList.get(currentTag).isOADing = false;
					startCountDown();
				}
				updateProgressUI(OADProgress, totalTime - (perTotalTime - timeLeft) + delayCheckTime);

				if (progress >= 1) {
					application.swDevicesList.get(currentTag).isOADing = false;
					if (OADProgress >= 1)
						return;

					 
				}

			}
		}
	};

	private void updateProgressUI(float progress, int secondsLeft) {
		mProgressBar.setProgress((int) (progress * 100));
		tv_percent.setText(String.format("%.1f", progress * 100) + "%");

		tv_time_left.setText(String.format("%02d:%02d",
				(int) (secondsLeft / 60), (int) secondsLeft
						- (int) (secondsLeft / 60) * 60));
	}

	protected void startCountDown() {
		final Timer timer = new Timer();
		final TimerTask timerTask = new TimerTask() {

			@Override
			public void run() {
				delayCheckTime--;
				Log.e(TAG, "startCountDown:" + delayCheckTime);
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						updateProgressUI(OADProgress, delayCheckTime);
						if (delayCheckTime <= 0) {
							timer.cancel();
							Log.e(TAG, "倒计时结束");
							Log.e(TAG, "version:"+application.swDevicesList.get(0).versionCode+" old:"+ oldVer[0]);
							
							if (application.swDevicesList.get(0).versionCode > oldVer[0]  ) {
								showDialogWithContent(getString(R.string.oad_success));
							} else {
								showDialogWithContent(getString(R.string.oad_fail));
							}
						}
					}
				});
			}
		};
	
		timer.scheduleAtFixedRate(timerTask, 0, 1 * 1000);
	}

	Runnable sendRunnable = new Runnable() {

		@Override
		public void run() {
			// 获取资源bin文件版本号
			String filePath;
			 
			filePath = application.swDevicesList.get(currentTag).versionChar == 'A' ? FW_FILE_MAIN_B
						: FW_FILE_MAIN_A;
			 
			addLog("开始 发送OAD数据 :"+filePath);
			//application.devicesList.get(currentTag).setOADPKT_Interval(10);
			//application.devicesList.get(currentTag).setOADInterval(15);
			application.swDevicesList.get(currentTag).setOADSleep(200);
			
			byte[] bytes = Util.loadAssetsFile(OADActivity.this,filePath);
			perTotalTime = application.swDevicesList.get(currentTag).startOAD(
					bytes);
			if (totalTime == 0) {
				totalTime = perTotalTime * needOADNum;
			}

			Log.e(TAG, " totalTime:" + perTotalTime);
			addLog(" Total Time:" + perTotalTime);
		}
	};

	private void showDialogWithContent(String content) {
		final MyDialog myDialog;
		myDialog = new MyDialog(this);
		myDialog.setContent(content);
		myDialog.setLeftButtonText(R.string.ok);
		myDialog.setCancelable(false);
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myDialog.dismiss();
				OADActivity.this.finish();
			}
		});
		myDialog.show();
	}

	private void addLog(String logString) {
		Log.e(TAG,logString);
		tv_log.setText(tv_log.getText().toString() + "\n"
				+ Util.formatTimeLongToString(System.currentTimeMillis()) + logString);
	}
}
